<template>
  <HeaderComponent />
  <div class="order-list-container">
    <!-- 批量删除按钮 -->
    <div class="batch-delete-container">
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 订单列表 -->
    <el-table
        :data="orders"
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
    >
      <!-- 添加多选框列 -->
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="canteenName" label="餐厅名称" width="150"></el-table-column>
      <el-table-column prop="seatId" label="餐桌" width="100"></el-table-column>
      <el-table-column prop="status" label="订单状态" width="100"></el-table-column>
      <el-table-column prop="orderAmount" label="订单金额" width="100"></el-table-column>
      <el-table-column prop="orderDate" label="下单时间" width="150">
        <template #default="scope">
          {{ formatDate(scope.row.orderDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="payAmount" label="支付金额" width="150"></el-table-column>
      <el-table-column prop="payDate" label="支付时间" width="150">
        <template #default="scope">
          {{ formatDate(scope.row.payDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="text" @click="viewOrderDetail(scope.row)">详情</el-button> &nbsp;&nbsp;|
          <el-button type="text" @click="handlePay(scope.row)">支付</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        style="margin-top: 20px; text-align: right;"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalOrders"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePageChange"
    />

    <!-- 每页条数选择器 -->
    <div class="page-size-selector">
      <span>每页展示：</span>
      <el-select v-model="pageSize" @change="handlePageSizeChange" style="width: 100px;">
        <el-option label="2 条" :value="2"></el-option>
        <el-option label="10 条" :value="10"></el-option>
        <el-option label="20 条" :value="20"></el-option>
        <el-option label="50 条" :value="50"></el-option>
      </el-select>
    </div>

    <!-- 订单详情弹框 -->
    <el-dialog v-model="dialogVisible" title="订单详情" width="50%">
      <div v-if="orderDetail">
        <p><strong>订单编号:</strong> {{ orderDetail.id }}</p>
        <p><strong>用户名称:</strong> {{ orderDetail.userName }}</p>
        <p><strong>餐厅名称:</strong> {{ orderDetail.canteenName }}</p>
        <p><strong>餐桌:</strong> {{ orderDetail.seatId }}</p>
        <p><strong>订单金额:</strong> {{ orderDetail.orderAmount }}</p>
        <p><strong>下单时间:</strong> {{ formatDate(orderDetail.orderDate) }}</p>
        <p><strong>支付金额:</strong> {{ orderDetail.payAmount }}</p>
        <p><strong>支付时间:</strong> {{ formatDate(orderDetail.payDate) }}</p>
        <p><strong>订单状态:</strong> {{ orderDetail.status }}</p>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 支付确认弹框 -->
    <el-dialog v-model="payDialogVisible" title="确认支付" width="30%">
      <div v-if="selectedOrder">
        <p><strong>订单编号:</strong> {{ selectedOrder.id }}</p>
        <p><strong>订单金额:</strong> {{ selectedOrder.orderAmount }}</p>
        <p><strong>支付金额:</strong> {{ selectedOrder.payAmount }}</p>
      </div>
      <template #footer>
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPay">确认支付</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import HeaderComponent from "@/components/HeaderComponent.vue";
import {GetOrders, PayOrder, DeleteOrder, GetOrderDetail} from "@/api"; // 引入 GetOrders、PayOrder、DeleteOrders 和 GetOrderDetail 方法
import dayjs from 'dayjs'; // 引入 dayjs
import { ElMessage, ElMessageBox } from 'element-plus';
import store from "@/store"; // 引入 ElMessage 和 ElMessageBox 用于提示

export default {
  name: 'OrderListVue',
  components: { HeaderComponent },
  setup() {
    // 订单数据
    const orders = ref([]);

    // 分页相关状态
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(5); // 每页显示的订单数量
    const totalOrders = ref(0); // 订单总数

    // 选中的订单
    const selectedOrders = ref([]);

    // 订单详情弹框相关状态
    const dialogVisible = ref(false); // 控制弹框显示
    const orderDetail = ref(null); // 订单详情数据

    // 支付确认弹框相关状态
    const payDialogVisible = ref(false); // 控制支付确认弹框显示
    const selectedOrder = ref(null); // 当前选中的订单

    // 时间格式化方法
    const formatDate = (dateString) => {
      if (!dateString) return ''; // 如果日期为空，返回空字符串
      return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
    };

    // 获取订单数据
    const fetchOrders = async () => {
      try {
        const response = await GetOrders(currentPage.value, pageSize.value);
        if (response.data.code === 200) {
          orders.value = response.data.data.orders; // 假设返回的数据中包含订单列表
          totalOrders.value = response.data.data.total; // 假设返回的数据中包含订单总数
          console.log("获取订单数据成功:", response);
          console.log("获取订单数据成功123:", orders.value);
        } else {
          console.error("获取订单数据失败:", response.data.message);
        }
        // if(localStorage.getItem('type') === 1){
        //
        // }else {
        //   const response = await GetAllOrders(currentPage.value, pageSize.value);
        //   if (response.data.code === 200) {
        //     orders.value = response.data.data.orders; // 假设返回的数据中包含订单列表
        //     totalOrders.value = response.data.data.total; // 假设返回的数据中包含订单总数
        //     console.log("获取订单数据成功:", response);
        //     console.log("获取订单数据成功123:", orders.value);
        //   } else {
        //     console.error("获取订单数据失败:", response.data.message);
        //   }
        // }


      } catch (error) {
        console.error("获取订单数据失败:", error);
      }
    };

    // 页面加载时获取订单数据
    onMounted(() => {
      fetchOrders();
    });

    // 分页改变时重新获取数据
    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
      fetchOrders();
    };

    // 每页条数改变时重新获取数据
    const handlePageSizeChange = (newSize) => {
      pageSize.value = newSize;
      currentPage.value = 1; // 重置为第一页
      fetchOrders(); // 重新获取数据
    };

    // 查看订单详情
    const viewOrderDetail = async (order) => {
      try {
        const response = await GetOrderDetail(order.id); // 调用 GetOrderDetail 方法获取订单详情
        if (response.data.code === 200) {
          orderDetail.value = response.data.data; // 假设返回的数据中包含订单详情
          dialogVisible.value = true; // 显示弹框
        } else {
          console.error("获取订单详情失败:", response.data.message);
        }
      } catch (error) {
        console.error("获取订单详情失败:", error);
      }
    };

    // 处理支付按钮点击
    const handlePay = (order) => {
      if (order.status === '已支付') {
        ElMessage.warning("该订单已支付，无需重复支付！");
      } else {
        selectedOrder.value = order; // 设置当前选中的订单
        payDialogVisible.value = true; // 显示支付确认弹框
      }
    };

    // 确认支付
    const confirmPay = async () => {
      try {
        const response = await PayOrder(selectedOrder.value.id); // 调用 PayOrder 方法支付订单
        if (response.data.code === 200) {
          const orderId = selectedOrder.value.id;
          const paymentResponse = await store.dispatch('order/reqPay', {
            orderId
          });
          if (paymentResponse) {
            console.log("res:", paymentResponse);
            // ElMessage.success('付款成功');
            // this.$router.push({ path: '/modules/orderList' });
          }

          // ElMessage.success("已确认支付");
          // ElMessage.success("支付成功");
          selectedOrder.value.status = '已支付'; // 更新订单状态
          selectedOrder.value.payDate = new Date().toISOString(); // 更新支付时间
          payDialogVisible.value = false; // 关闭支付确认弹框
          fetchOrders(); // 重新获取订单数据
          console.log("支付成功:", response);
        } else if (response.data.code === 400) {
          // 处理状态码为 400 的情况
          ElMessage.error(response.data.errorMsg || "支付失败：订单不属于您");
          payDialogVisible.value = false; // 关闭支付确认弹框
        } else {
          // 处理其他错误状态码
          ElMessage.error("支付失败：" + (response.data.errorMsg || "未知错误"));
        }
      } catch (error) {
        // 捕获网络请求失败或其他异常
        console.error("支付失败:", error);
        ElMessage.error("支付失败，请稍后重试");
      }
    };

    // 处理选中订单
    const handleSelectionChange = (selection) => {
      selectedOrders.value = selection; // 更新选中的订单
    };

    // 批量删除订单
    const handleBatchDelete = () => {
      if (selectedOrders.value.length === 0) {
        ElMessage.warning("请选择要删除的订单！");
        return;
      }

      // 将选中的订单 ID 用逗号拼接成字符串
      const ids = selectedOrders.value.map(order => order.id).join(',');
      console.log("批量删除订单:", ids);

      ElMessageBox.confirm('确定要删除选中的订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(async () => {
            try {
              // 调用批量删除接口
              const response = await DeleteOrder(ids); // 假设 DeleteOrders 是批量删除接口
              await fetchOrders(); // 重新获取订单数据
              console.log("批量删除订单:", ids);
              if (response.data.code === 200) {
                ElMessage.success("删除成功");
              } else {
                ElMessage.error("删除失败：" + response.data.message);
              }
            } catch (error) {
              console.error("删除失败:", error);
              ElMessage.error("删除失败，请稍后重试");
            }
          })
          .catch(() => {
            ElMessage.info("已取消删除");
          });
    };

    return {
      orders,
      currentPage,
      pageSize,
      totalOrders,
      handlePageChange,
      handlePageSizeChange,
      formatDate,
      viewOrderDetail,
      handlePay,
      handleSelectionChange,
      handleBatchDelete,
      dialogVisible,
      orderDetail,
      payDialogVisible,
      selectedOrder,
      confirmPay,
    };
  },
};
</script>

<style scoped>
.order-list-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.batch-delete-container {
  margin-bottom: 20px;
  text-align: right;
}

.page-size-selector {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.filter-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.filter-item {
  flex: 1;
}

.el-table {
  margin-top: 20px;
}

.el-button--text {
  color: #007bff;
}

.el-button--text:hover {
  color: #0056b3;
}
</style>
